import axios from "axios";
import { ElMessage } from "element-plus";
import { Session } from "@/utils/storage";

export const downloadFile = (
  method: any,
  url: any,
  data: any,
  fileName: any
) => {
  let _data = null;
  let _params = null;
  if (method === "GET") {
    _params = data;
  } else {
    _data = data;
  }
  return axios({
    url,
    method,
    params: _params,
    data: _data,
    responseType: "blob",
    headers: {
      Token: Session.get("token"),
    },
    timeout: 60000,
  })
    .then((res: any) => {
      if (res && res.status === 200 && res.data) {
        const { data, headers } = res;
        let setFileName = fileName;
        // 此处当返回json文件时需要先对data进行JSON.stringify处理，其他类型文件不用做处理
        const blob = new Blob([data], { type: headers["content-type"] });
        const dom = document.createElement("a");
        const downUrl = window.URL.createObjectURL(blob);
        dom.href = downUrl;
        dom.download = decodeURIComponent(setFileName);
        dom.style.display = "none";
        document.body.appendChild(dom);
        dom.click();
        dom.parentNode?.removeChild(dom);
        window.URL.revokeObjectURL(url);
      } else {
        ElMessage.error(res.msg || "下载失败！");
      }
    })
    .catch((err) => {
      ElMessage.error("下载失败！");
    });
};

// 实例
// downloadFile('POST', `${state.tableData.config.baseUrl}/v0/attend/daily/exportCountOrg`, { date: state.tableData.param.date, day: state.tableData.param.day }, '安防综合管理平台-部门汇总表')
